package top.frsf.reggie.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import top.frsf.reggie.entity.Category;
import top.frsf.reggie.excpetion.BusinessException;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @Author FRSF
 * @Date 2023/1/12 0:00
 * @Description 全局异常处理器
 */

@Slf4j
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceptionHandler {

    /**
     * @Author: FRSF
     * @Date: 2023/1/12 0:16
     * @Description 数据库常见异常处理
     * @param ex: 异常类
     * @return: top.frsf.reggie.common.R<java.lang.String>
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> SQLexceptionHandler(SQLIntegrityConstraintViolationException ex) {
        log.warn("异常：SQLIntegrityConstraintViolationException");

        // unique索引不唯一异常
        if (ex.getMessage().contains("Duplicate entry")) {
            String[] split = ex.getMessage().split(" ");
            String msg = "unique字段：" + split[2].substring(1, split[2].length() - 1) + " 已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }


    @ExceptionHandler(BusinessException.class)
    public R<String> bunessExceptionHandler(BusinessException ex) {
        log.warn("自定义业务异常:BusinessException--" + ex.getMessage());
        return R.error(ex.getMessage());
    }


}
